<template>
  <el-dialog @close="close" v-model="dialogVisible" :title="title" width="50%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
      <el-form-item label="设备平台" prop="type_id">
        <el-select v-model="ruleForm.type_id" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in typeArr" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="下载模版文件">
        <el-button type="primary" style="margin-right: 2px" @click="downmodel()">下载模版文件</el-button>
      </el-form-item>
      <el-form-item label="上传文件" prop="file">
        <el-upload
          ref="upload"
          class="upload-demo"
          :limit="1"
          :on-exceed="handleExceed"
          accept=".xls,.xlsx"
          :auto-upload="false"
          :on-change="addFileMain"
        >
          <template #trigger>
            <el-button type="primary" style="margin-right: 2px">请选择文件</el-button>
          </template>
          <el-button class="ml-3" type="success" @click="submitUpload"> 点击上传 </el-button>
          <template #tip>
            <div class="el-upload__tip text-red" v-if="ruleForm.files">
              已上传至：{{ ruleForm.files }}
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleConfim(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
  <script lang="ts" setup>
import {
  ElMessageBox,
  ElMessage,
  FormInstance,
  ElNotification,
  UploadInstance,
  UploadProps,
  UploadRawFile,
} from 'element-plus'
import { reactive, ref } from 'vue'
import { deptData } from '@/mock/system'
import { importEquipment, platformList, roomList, uploadFun } from '@/api/admin'
import { useRoute } from 'vue-router'
import { genFileId } from 'element-plus'
const route = useRoute()
const ruleFormRef = ref<FormInstance>()
const dialogVisible = ref<boolean>(false)
const deptDataOptions = ref(deptData)
const title = ref('导入设备')
const rules = reactive({
  type_id: [{ required: true, message: '请选择设备平台', trigger: 'change' }],
  // name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  // sn: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  // platform_id: [{ required: true, message: '请选择医院', trigger: 'change' }],
  // room_id: [{ required: true, message: '请选择医院', trigger: 'change' }],
})
const ruleForm = reactive({
  type_id: Number(route.query.id) || '',
  files: '',
})
const saveLoading = ref(false)
const emit = defineEmits(['refresh'])
const platData = ref()
const roomData = ref()
const props = defineProps({
  typeArr: {
    type: Array,
    default: [],
  },
})
const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const addFileMain = (file) => {
  let raw = file.raw
  let formDate = new FormData()
  formDate.append('file', raw)
  formDate.append('upload_type', 'local')
  formDate.append('timestamp', '12345678910')
  formDate.append('nonceStr', 'nonceStr')
  formDate.append('sign', 'sign')
  if (raw != null) {
    uploadFun(formDate).then((res) => {
      if (res.code == 200) {
        ruleForm.files = res.data.url
        console.log('ruleForm.files', res.data.url)
      }
    })
  }
}
const submitUpload = () => {
  upload.value!.submit()
}
function close() {
  ruleFormRef.value.resetFields()
  Object.keys(ruleForm).forEach((key) => {
    if (key == 'status') ruleForm[key] = 1
    else if (key == 'type_id') ruleForm[key] = Number(route.query.id) || ''
    else if (key == 'files') ruleForm[key] = ''
    else if (key == 'config')
      ruleForm[key] = {
        autoTime: [
          {
            openTime: '',
            closeTime: '',
          },
        ],
      }
    else ruleForm[key] = null
  })
}

const show = (item = {}) => {
  title.value = '导入设备'

  dialogVisible.value = true
  getPlatList()
}
//医院
const getPlatList = () => {
  platformList({ selectFields: 'id,name' }).then((res) => {
    if (res.code == 200) {
      platData.value = res.data
    }
  })
}
const handlePlatChange = (val) => {
  getRoomList(val)
}
//房间列表
const getRoomList = (id) => {
  let filter = JSON.stringify({ platform_id: id })
  roomList({ selectFields: 'id,name', filter: filter }).then((res) => {
    if (res.code == 200) {
      roomData.value = res.data
    }
  })
}

const handleConfim = async (done: () => void) => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      saveLoading.value = true
      //新增
      importEquipment(ruleForm).then((res) => {
        if (res.code == 200) {
          ElNotification({
            title: '添加成功',
            message: res.msg,
            type: 'success',
          })
          emit('refresh')
        }
        upload.value.clearFiles()
        dialogVisible.value = false
        saveLoading.value = false
      })
    }
  })
}
const downmodel = () =>{
  // qumodel.xlsx
  window.open('/public/download/qumodel.xlsx');
}
const addAutoTime = () => {
  let length = ruleForm.config.autoTime.length
  if (!ruleForm.config.autoTime[length - 1].openTime) {
    ElMessage.warning('请选择开启时间！')
    return
  }
  if (!ruleForm.config.autoTime[length - 1].closeTime) {
    ElMessage.warning('请选择关闭时间！')
    return
  }
  ruleForm.config.autoTime.push({
    openTime: '',
    closeTime: '',
  })
}
const delAutoTime = (index) => {
  ruleForm.config.autoTime.splice(index, 1)
}

defineExpose({
  show,
})
</script>
  <style lang="scss" scoped>
</style>
  
  